﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        #region 变量定义
        bool uart_Open_flag = true; //判断串口是否打开
        SerialPort uartport = new SerialPort();
        public static string comData = null;//接收串口并且解析
        #endregion
        /// <summary>
        /// 初始化窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 


        private void Form1_Load(object sender, EventArgs e)
        {
            //设计串口号 com1
            this.comboBox1.SelectedIndex = 0;
            //设置波特率 9600
            this.comboBox2.SelectedIndex = 0;
            //设置数据位 8
            this.comboBox3.SelectedIndex = 1;
            //设置校验位 None
            this.comboBox4.SelectedIndex = 0;
            //设置停止位 1
            this.comboBox5.SelectedIndex = 0;
        }
        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            OpenPort();
        }

        private void OpenPort()
        {
            if (uart_Open_flag == true)//判断串口成功
            {
                uartport.DtrEnable = true;
                //如果为 true，则启用数据终端就绪 (DTR)；否则为 false。 默认为 false。
                uartport.RtsEnable = true;
                //如果为 true，则启用请求发送 (RTS)；否则为 false。 默认为 false
                this.button1.Text = "关闭串口";
                uartport.PortName = this.comboBox1.Text;                        //设置串口号
                uartport.BaudRate = int.Parse(this.comboBox2.Text);            //设置波特率
                uartport.DataBits = int.Parse(this.comboBox3.Text);             //设置数据位

                uartport.StopBits = (StopBits)int.Parse(this.comboBox5.Text);   //设置停止位
                uartport.Open();
                uartport.DataReceived += new SerialDataReceivedEventHandler(uartport_DataRec);

                uart_Open_flag = false;
            }
            else
            {
                this.button1.Text = "打开串口";
                uartport.Close();
                uart_Open_flag = true;
            }

            void uartport_DataRec(object sender,SerialDataReceivedEventArgs e) 
            {
                //将byte数组转化为字符
                int count = uartport.BytesToRead;
                byte[] rec = new byte[count];

                //读取数据
                uartport.Read(rec, 0, count);

                //判断选择显示模式
                if (this.radioButton1.Checked) //字符串模式
                {
                    //将Byte数据转化为字符串
                    string stcRec = Encoding.Default.GetString(rec);

                    Control.CheckForIllegalCrossThreadCalls = false;//避免线程占用
                    if (checkBox1.Checked)//换行显示
                    {
                        this.textBox1.Text += stcRec + "\r\n";//显示内容换行
                    }
                    else
                    {
                        this.textBox1.Text += stcRec; //不加回车换行
                    }
                }
                if (this.radioButton2.Checked) //HEX模式
                {
                    if (checkBox1.Checked)//换行显示
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            textBox1.Text += byteTohexstr(rec) + "\r\n";
                            comData = byteTohexstr(rec);


                        }));
                    }
                    else
                    {
                        this.Invoke(new MethodInvoker(() =>
                        {
                            textBox1.Text += byteTohexstr(rec) ;
                            comData = byteTohexstr(rec);


                        }));
                    }
                    ExtracData();//提取串口数据
                }
            }

        }


        public static string byteTohexstr(byte[] bytes)
        {
            string str = "";//构建返回字符串
            if (bytes != null)
            {
                for (int temp = 0; temp < bytes.Length; temp++)//循环字符转化函数
                {
                    str += bytes[temp].ToString("x2")+"";
                }

            }
            return str;
        }
        public static void ExtracData()
        {
            int[] intArray = { };
            string[] strArray = { };
            strArray = comData.Split();//提取返回数据到数组中
            strArray = strArray.Take(strArray.Count()).ToArray();//从数组中删除最后一项
            for(int temp = 0;temp < strArray.Length;temp++)
            {
                try
                {
                    intArray[temp] = Convert.ToInt32(strArray);
                }
                catch (Exception)
                { 
                }
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (radioButton2.Checked)//HEX模式
                {
                    byte[] d = strTohexByte(this.textBox2.Text);
                    uartport.Write(d, 0, d.Length);//发送数据
                }
                if (radioButton1.Checked)//字符串形式
                {
                    byte[] Send_buf = new byte[1024*1024];//形成数组形式
                    //将字符转化byte数组
                    Send_buf = Encoding.Default.GetBytes(this.textBox2.Text);
                    //发送数据
                    uartport.Write(Send_buf, 0, Send_buf.Length);
                }
            }
            catch (Exception)
            { 
            }
            
        }
        private byte[] strTohexByte(string HEXstring)//字符串转化
        {
            HEXstring = HEXstring.Replace(" ", "");
            //假如是是HEX的话可以被二整除 不能就加空字符
            if (HEXstring.Length % 2 != 0)
            {
                HEXstring += "";
            }
            byte[] returnbyte = new byte[HEXstring.Length / 2];//缓存数据集
                                                               //转化16进制 
            for (int i = 0; i < returnbyte.Length; i++)
            {
                returnbyte[i] = Convert.ToByte(HEXstring.Substring(i * 2, 2).Replace(" ", ""), 16);
            }
            return returnbyte;//发回数据

        }
        /// <summary>
        /// 清空接收
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = "";
        }
    }

    
}
